package com.adk.backend.service.impl;

import com.adk.backend.mapper.DownloadMapper;
import com.adk.backend.service.DownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 下载中心服务实现
 */
@Slf4j
@Service
public class DownloadServiceImpl implements DownloadService {
    
    @Autowired
    private DownloadMapper downloadMapper;
    
    // 运输方式映射
    private static final Map<Integer, String> SHIP_TYPE_MAP = new HashMap<>();
    static {
        SHIP_TYPE_MAP.put(1, "沙特空运");
        SHIP_TYPE_MAP.put(2, "沙特海运拼柜");
        SHIP_TYPE_MAP.put(3, "阿联酋空运");
        SHIP_TYPE_MAP.put(4, "阿联酋海运");
        SHIP_TYPE_MAP.put(7, "沙特海运整柜");
    }
    
    // 交货方式映射
    private static final Map<Integer, String> ORDER_TYPE_MAP = new HashMap<>();
    static {
        ORDER_TYPE_MAP.put(1, "自寄");
        ORDER_TYPE_MAP.put(2, "上门提货");
        ORDER_TYPE_MAP.put(3, "自寄东莞仓");
        ORDER_TYPE_MAP.put(4, "自寄义乌仓");
        ORDER_TYPE_MAP.put(5, "自寄福永空运仓");
        ORDER_TYPE_MAP.put(6, "自寄广州仓");
        ORDER_TYPE_MAP.put(7, "自寄香港仓");
    }
    
    // 送仓类型映射
    private static final Map<Integer, String> DES_ADD_MAP = new HashMap<>();
    static {
        DES_ADD_MAP.put(1, "Aiduk 上架");
        DES_ADD_MAP.put(2, "Aiduk-DS");
        DES_ADD_MAP.put(3, "亚马逊");
        DES_ADD_MAP.put(4, "Noon");
        DES_ADD_MAP.put(5, "私人地址");
        DES_ADD_MAP.put(6, "自提");
    }
    
    // 仓库发货类型映射
    private static final Map<Integer, String> WH_SHIP_TYPE_MAP = new HashMap<>();
    static {
        WH_SHIP_TYPE_MAP.put(1, "打小包");
        WH_SHIP_TYPE_MAP.put(2, "Cou证书");
        WH_SHIP_TYPE_MAP.put(3, "Cargo");
        WH_SHIP_TYPE_MAP.put(4, "B2C");
        WH_SHIP_TYPE_MAP.put(5, "退回");
    }
    
    // 票结方式映射
    private static final Map<Integer, String> PT_MAP = new HashMap<>();
    static {
        PT_MAP.put(0, "票结");
        PT_MAP.put(1, "半月结");
        PT_MAP.put(2, "月结");
    }
    
    @Override
    public List<Map<String, Object>> downloadOrderData(Map<String, Object> params) {
        List<Map<String, Object>> list = downloadMapper.selectOrderDataForDownload(params);
        
        // 格式化数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("MM-dd HH:mm");
        
        for (Map<String, Object> item : list) {
            // 格式化入库日期
            if (item.get("recv_time") != null) {
                Integer recvTime = (Integer) item.get("recv_time");
                if (recvTime > 0) {
                    item.put("recv_time", dateFormat.format(new Date(recvTime * 1000L)));
                } else {
                    item.put("recv_time", "");
                }
            }
            
            // 格式化交货方式
            if (item.get("order_type") != null) {
                Integer orderType = (Integer) item.get("order_type");
                item.put("order_type", ORDER_TYPE_MAP.getOrDefault(orderType, ""));
            }
            
            // 处理入仓号（如果有多发货，显示次数）
            String orderNo = (String) item.get("order_no");
            Integer shippedTimes = (Integer) item.get("shippedtimes");
            if (shippedTimes != null && shippedTimes > 0) {
                item.put("order_no", orderNo + "-" + shippedTimes);
            }
            
            // 处理送仓类型
            Integer desAdd = (Integer) item.get("des_add");
            if (desAdd != null) {
                if (desAdd == 3) {
                    // 亚马逊，显示FBA单号
                    item.put("des_add", item.get("fba_no") != null ? item.get("fba_no") : "");
                } else {
                    item.put("des_add", DES_ADD_MAP.getOrDefault(desAdd, ""));
                }
            }
            
            // 处理出货方式（根据运输方式判断）
            Integer shipType = (Integer) item.get("ship_type");
            if (shipType != null && (shipType == 1 || shipType == 3)) {
                // 空运
                Integer shippedType = (Integer) item.get("shipped_type");
                if (shippedType != null && shippedType > 0) {
                    item.put("shipped_type", WH_SHIP_TYPE_MAP.getOrDefault(shippedType, ""));
                } else {
                    item.put("shipped_type", "");
                }
            } else {
                // 海运
                Integer isBrandRemarks = (Integer) item.get("is_brand_remarks");
                item.put("shipped_type", isBrandRemarks != null ? isBrandRemarks : "");
            }
            
            // 处理备注
            if (shippedTimes != null && shippedTimes == 0) {
                item.put("remarks", item.get("remarks"));
            } else {
                item.put("remarks", item.get("slremarks"));
            }
            
            // 处理报关
            Integer declareType = (Integer) item.get("declare_type");
            if (declareType != null && declareType == 1) {
                item.put("declare_type", "是");
            } else {
                item.put("declare_type", "");
            }
            
            // 如果是多次发货，清空箱数和计费重
            if (shippedTimes != null && shippedTimes != 0) {
                item.put("total_ctns", "");
                item.put("ship_weigth", "");
            }
            
            // 格式化出库日期
            Integer txDate = (Integer) item.get("tx_date");
            Integer newStatus = (Integer) item.get("new_status");
            if (newStatus != null && newStatus > 0 && txDate != null && txDate > 0) {
                item.put("tx_date", dateFormat.format(new Date(txDate * 1000L)));
            } else {
                item.put("tx_date", "");
            }
            
            // 处理最新动态
            if (newStatus != null && newStatus > 0) {
                item.put("new_status", item.get("new_status_name"));
            } else {
                Integer status = (Integer) item.get("status");
                if (status != null && status == 0) {
                    item.put("new_status", "待提交");
                } else {
                    item.put("new_status", item.get("status_name"));
                }
            }
            
            // 处理时间
            Integer lastStatusTime = (Integer) item.get("last_status_time");
            Integer slAddTime = (Integer) item.get("sladd_time");
            if (newStatus != null && newStatus > 6) {
                if (slAddTime != null && slAddTime > 0) {
                    item.put("last_status_time", datetimeFormat.format(new Date(slAddTime * 1000L)));
                } else {
                    item.put("last_status_time", "");
                }
            } else {
                if (lastStatusTime != null && lastStatusTime > 0) {
                    item.put("last_status_time", datetimeFormat.format(new Date(lastStatusTime * 1000L)));
                } else {
                    item.put("last_status_time", "");
                }
            }
            
            // 格式化运输方式
            if (shipType != null) {
                item.put("ship_type", SHIP_TYPE_MAP.getOrDefault(shipType, ""));
            }
            
            // 移除不需要的字段
            item.remove("shippedtimes");
            item.remove("sladd_time");
            item.remove("fba_no");
            item.remove("slremarks");
            item.remove("status");
            item.remove("new_status_name");
            item.remove("is_brand_remarks");
        }
        
        return list;
    }
    
    @Override
    public List<Map<String, Object>> downloadBillingData(Map<String, Object> params) {
        // 默认查询ship_type in (1,2,3,4,7)
        if (params.get("shipTypes") == null) {
            params.put("shipTypes", Arrays.asList(1, 2, 3, 4, 7));
        }
        
        List<Map<String, Object>> list = downloadMapper.selectBillingDataForDownload(params);
        
        // 格式化数据
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
        for (Map<String, Object> item : list) {
            // 合并客户代码和简称
            String cusCode = (String) item.get("cus_code");
            String cusShort = (String) item.get("cus_short");
            if (cusCode != null && cusShort != null) {
                item.put("cus_code", cusCode + "(" + cusShort + ")");
            }
            item.remove("cus_short");
            
            // 格式化入库日期
            Integer recvTime = (Integer) item.get("recv_time");
            if (recvTime != null && recvTime > 0) {
                item.put("recv_time", dateFormat.format(new Date(recvTime * 1000L)));
            } else {
                item.put("recv_time", "");
            }
            
            // 格式化收款状态
            Integer paid = (Integer) item.get("paid");
            if (paid != null) {
                if (paid == 1) {
                    item.put("paid", "已收款");
                } else if (paid == 2) {
                    item.put("paid", "收部份");
                } else {
                    item.put("paid", "");
                }
            }
            
            // 格式化收款日期
            Integer paidTime = (Integer) item.get("paid_time");
            if (paidTime != null && paidTime > 1) {
                item.put("paid_time", dateFormat.format(new Date(paidTime * 1000L)));
            } else {
                item.put("paid_time", "");
            }
            
            // 格式化运输方式
            Integer shipType = (Integer) item.get("ship_type");
            if (shipType != null) {
                item.put("ship_type", SHIP_TYPE_MAP.getOrDefault(shipType, ""));
            }
            
            // 格式化票结方式
            Integer pt = (Integer) item.get("pt");
            if (pt != null) {
                item.put("pt", PT_MAP.getOrDefault(pt, ""));
            }
            
            // 处理提单号（从bl_details获取）
            String blNo = (String) item.get("bl_no");
            if (blNo == null || blNo.isEmpty()) {
                item.put("bl_no", "");
            }
            
            // 处理签收日期（从recvd_list获取）
            String recvDate = (String) item.get("recv_date");
            String recvDateStr = "";
            if (recvDate != null && !recvDate.isEmpty()) {
                try {
                    // 如果recv_date是时间戳，转换为日期字符串
                    if (recvDate.matches("\\d+")) {
                        Integer recvDateInt = Integer.parseInt(recvDate);
                        if (recvDateInt > 0) {
                            recvDateStr = dateFormat.format(new Date(recvDateInt * 1000L));
                        }
                    } else {
                        recvDateStr = recvDate;
                    }
                } catch (Exception e) {
                    recvDateStr = recvDate;
                }
            }
            
            // 重命名字段以匹配PHP导出格式
            item.put("Bill_ID", item.get("id"));
            item.put("客户", item.get("cus_code"));
            item.put("入仓号", item.get("order_no"));
            item.put("入库日期", item.get("recv_time"));
            item.put("账单日期", item.get("bill_date"));
            item.put("货币", item.get("currency_name"));
            item.put("账单金额", item.get("total_amount"));
            item.put("收款状态", item.get("paid"));
            item.put("收款日期", item.get("paid_time"));
            item.put("收款账户", item.get("bank_name"));
            item.put("运输方式", item.get("ship_type"));
            item.put("备注", item.get("remarks"));
            item.put("业务", item.get("username"));
            item.put("签收日期", recvDateStr);
            item.put("账期", item.get("pt"));
            item.put("开发", item.get("yw_user"));
            item.put("提单号", item.get("bl_no"));
            item.put("柜号", item.get("loading_no"));
        }
        
        return list;
    }
}

